package com.yky.action.admin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;

import com.yky.action.base.BaseActionSupport;
import com.yky.entity.EthicsCommitteeRecords;
import com.yky.entity.Organization;
import com.yky.entity.OrganizationRecords;
import com.yky.entity.Province;
import com.yky.entity.User;
import com.yky.service.admin.EthicsCommitteeRecordsService;
import com.yky.service.admin.OrganizationRecordsService;
import com.yky.service.admin.OrganizationService;
import com.yky.service.admin.ProvinceService;
import com.yky.service.admin.UserService;
import com.yky.utils.JsonUtil;
import com.yky.utils.base.DateUtils;

@ParentPackage("perInterceptor")
@InterceptorRefs( { @InterceptorRef("sessionStack") })
@Namespace(value = "/ethicsCommittee_records")
public class EthicsCommitteeRecordsAction extends BaseActionSupport {

	private static final long serialVersionUID = 1L;

	@Autowired
	private OrganizationRecordsService organizationRecordsService;
	@Autowired
	private OrganizationService organizationService;
	@Resource
	private ProvinceService provinceService;
	@Resource
	private UserService userService;
	@Autowired
	private EthicsCommitteeRecordsService ethicsCommitteeRecordsService;

	private Integer id;

	private String searchText;
	private String pageIndex;
	private String pageShowCount;

	private String name; // 伦理委员会名称
	private String memberName; // 伦理委员会组成成员名单
	private String isConstitution; // 是否有伦理委员会章程
	private String isWorkingSystem; // 是否有工作制度或工作程序
	private String telphone; // 伦理委员会联系电话
	private String email; // 伦理委员会电子邮箱
	private String attachmentPath; // 批准附件
	private String practiceRegistrationAuthority; // 备案执业登记机关

	private Organization organization; // 所属机构
	private String province; // 所属省份
	private EthicsCommitteeRecords ethicsCommitteeRecords;

	private String status; // 状态（0-未审核 1-审核通过 2-审核未通过）
	private String reason; // 原因
	private Integer state; // 通过状态

	public String deleteEthicsCommitteeRecords() throws Exception {
		User aUser = (User) getSession().getAttribute("user");
		if (aUser == null) {
			return null;
		}
		if (id != null) {
			ethicsCommitteeRecordsService.deleteEntity(id);
			super.pringWriterToPage("success");
			return null;
		}
		return null;
	}

	public String findEthicsCommitteeRecords() throws Exception {
		EthicsCommitteeRecords aEthicsCommitteeRecords = ethicsCommitteeRecordsService
				.find(id);
		String content = JsonUtil.formatToJson(aEthicsCommitteeRecords);
		super.pringWriterToPage(content);
		return null;
	}

	// 编辑伦理备案信息
	public String editEthicsCommitteeRecords() throws Exception {
		User aUser = (User) getSession().getAttribute("user");
		if (aUser == null) {
			return null;
		}
		if (id != null) {
			EthicsCommitteeRecords aEthicsCommitteeRecords = ethicsCommitteeRecordsService.find(id);
			aEthicsCommitteeRecords.setName(name);
			aEthicsCommitteeRecords.setMemberName(memberName);
			aEthicsCommitteeRecords.setIsConstitution(isConstitution);
			aEthicsCommitteeRecords.setIsWorkingSystem(isWorkingSystem);
			aEthicsCommitteeRecords.setTelphone(telphone);
			aEthicsCommitteeRecords.setEmail(email);
			aEthicsCommitteeRecords.setAttachmentPath(attachmentPath);
			aEthicsCommitteeRecords.setPracticeRegistrationAuthority(practiceRegistrationAuthority);
			aEthicsCommitteeRecords.setOrganization(aUser.getOrganization());
			aEthicsCommitteeRecords.setProvince(aUser.getProvince());
			//zf 2017年2月16日17:18:25 start 
			aEthicsCommitteeRecords.setStatus("-1");
			//zf 2017年2月16日17:18:25 end  
			aEthicsCommitteeRecords.setCreateUser(aUser);
			aEthicsCommitteeRecords.setCreateTime(DateUtils.getDateTime());
			ethicsCommitteeRecordsService.updateEntity(aEthicsCommitteeRecords);
			super.pringWriterToPage("success");
			return null;
		} else {
			EthicsCommitteeRecords aEthicsCommitteeRecords = new EthicsCommitteeRecords();
			aEthicsCommitteeRecords.setName(name);
			aEthicsCommitteeRecords.setMemberName(memberName);
			aEthicsCommitteeRecords.setIsConstitution(isConstitution);
			aEthicsCommitteeRecords.setIsWorkingSystem(isWorkingSystem);
			aEthicsCommitteeRecords.setTelphone(telphone);
			aEthicsCommitteeRecords.setEmail(email);
			aEthicsCommitteeRecords.setAttachmentPath(attachmentPath);
			aEthicsCommitteeRecords
					.setPracticeRegistrationAuthority(practiceRegistrationAuthority);
			aEthicsCommitteeRecords.setOrganization(aUser.getOrganization());
			aEthicsCommitteeRecords.setProvince(aUser.getProvince());
			//zf 2017年2月16日17:18:25 start 
			aEthicsCommitteeRecords.setStatus("-1");
			//zf 2017年2月16日17:18:25 end
			aEthicsCommitteeRecords.setCreateUser(aUser);
			aEthicsCommitteeRecords.setCreateTime(DateUtils.getDateTime());
			ethicsCommitteeRecordsService.saveEntity(aEthicsCommitteeRecords);
			super.pringWriterToPage("success");
			return null;
		}
	}
	/**
	 * 2017年2月16日17:29:07
	 * @author zf  start
	 * @throws 伦理委员会备案列表提交
	 */
	// 编辑伦理备案信息
		public String editEthicsCommitteeRecordsSubmit() throws Exception {
			User aUser = (User) getSession().getAttribute("user");
			if (aUser == null) {
				return null;
			}
				List<EthicsCommitteeRecords> EthicsCommitteeRecordsList =ethicsCommitteeRecordsService.findEntityList();
				for (int i = 0; i < EthicsCommitteeRecordsList.size(); i++) {
					EthicsCommitteeRecords ethicsCommitteeRecords= EthicsCommitteeRecordsList.get(i);
					if(ethicsCommitteeRecords.getOrganization().getId().equals(aUser.getOrganization().getId())&&!ethicsCommitteeRecords.getStatus().equals("1")&&!ethicsCommitteeRecords.getStatus().equals("2")){
						ethicsCommitteeRecords.setStatus("0");
						ethicsCommitteeRecordsService.updateEntity(ethicsCommitteeRecords);
					}
				}
				super.pringWriterToPage("success");
				return null;
			
		}
	/** end  */
	// 通过用户查询该用户所属机构的伦理备案信息
	public String getEthicsCommitteeRecordsList() throws Exception {
		User aUser = (User) getSession().getAttribute("user");
		if (aUser != null) {
			Organization aOrganization = aUser.getOrganization();
			List<EthicsCommitteeRecords> list = ethicsCommitteeRecordsService
					.findByPropertys("o.organization=?",
							new Object[] { aOrganization });
			String content = JsonUtil.formatToJson(list);
			super.pringWriterToPage(content);
			return null;
		}
		return null;
	}

	public String getPageCount() throws Exception {
		if (searchText == null || "机构名称".equals(searchText)) {
			searchText = "";
		}
		int count = searchEthicsCommitteeRecords(searchText,province);
		String content = JsonUtil.formatToJson(count);
		super.pringWriterToPage(content);
		return null;
	}

	public int searchEthicsCommitteeRecords(String searchText,String provinceCode) {
		if(searchText==null) {
			searchText = "";
		}
		if(provinceCode==null) {
			provinceCode = "";
		}
		//int result = 0;
//		List<EthicsCommitteeRecords> list = new ArrayList<EthicsCommitteeRecords>();
		//查询记录总数
		List r = ethicsCommitteeRecordsService.findBySQL(" select count(distinct( t1.organization_id)) as count "+
												  " from work_ethics_committee_records t1 "+
												  " left join work_organization t2 on t1.organization_id=t2.id "+
												  " left join sys_province t3 on t1.province_id=t3.code "+
												  " where t1.status='"+state+"' and t2.name like '%"+ searchText +"%' and t1.province_id like '%"+ provinceCode +"%' ");
	//	System.out.println("记录总数======="+r.get(0));
		
		//列表页
//		List<Object[]> r2 = ethicsCommitteeRecordsService.findBySQL("select distinct(t1.organization_id) as organization_id,t2.name as organization_name,t2.create_time,t2.organ_level,t3.name as province_name "+
//				  " from work_ethics_committee_records t1 "+
//				  " left join work_organization t2 on t1.organization_id=t2.id "+
//				  " left join sys_province t3 on t1.province_id=t3.code "+
//				  " where t1.status='1'");
//		if (null != r2 && r2.size() > 0) {
//			for (Object[] numObj : r2) {
//				//System.out.println(numObj[0] + "/" + numObj[1]+ "/" + numObj[2]+ "/" + numObj[3]+ "/" + numObj[4]);
//			}
//			result = r2.size();
//		}
		
//		try{
//			if (state == 1) {
//				if (null != province && province.length() > 0) {
//					list = ethicsCommitteeRecordsService
//							.findByPropertys(
//									"o.organization.name like ? and o.status=? and o.organization.province.code=?",
//									new Object[] { "%" + searchText + "%", state+"", province });
//				} else {
//					list = ethicsCommitteeRecordsService.findByPropertys(
//							"o.organization.name like ? and o.status=?",
//							new Object[] { "%" + searchText + "%", state+"" });
//				}
//			} else if (state == 2) {
//				User userS = (User) getSession().getAttribute("user");
//				list = ethicsCommitteeRecordsService
//						.findByPropertys(
//								"o.organization.name like ? and o.organization.province.code=? and o.status=?",
//								new Object[] { "%" + searchText + "%",
//										userS.getProvince().getCode(), 0+"" });
//
//			}
//			if (null != list) {
//				result = Integer.valueOf(String.valueOf(list.size()));
//			}
//		}catch(Exception e) {
//			e.printStackTrace();
//		}
		
		return (int)r.get(0);
	}

	public String getPageList() throws Exception {
		// TODO Auto-generated method stub
		if (searchText == null || "机构名称".equals(searchText)) {
			searchText = "";
		}
		List<Map<Object, Object>> result = new ArrayList<Map<Object, Object>>();
		List<EthicsCommitteeRecords> list = null;
		List<Object[]> Objectlist = null;
		try {

			int page = Integer.valueOf(pageIndex);
			int maxResult = Integer.valueOf(pageShowCount);
			int firstResult = maxResult * page;
		//	if(searchText.equals("")&&province.equals("")){
				Objectlist=searchEthicsCommitteeList(searchText,province);
			/*}else{
				list = searchEthicsCommitteeRecords(searchText, firstResult,maxResult);
			}*/
			if (null != list) {
					Map<Object, Object> map = null;
					for (EthicsCommitteeRecords objRecodes : list) {
						Organization obj = objRecodes.getOrganization();
						map = new HashMap<Object, Object>();
						map.put("id", obj.getId());
						map.put("name", obj.getName());
						map.put("organLevel", obj.getOrganLevel());
						map.put("province", obj.getProvince().getShortName());
						map.put("status", objRecodes.getStatus());
						map.put("createdate", obj.getCreateTime());
						result.add(map);
				}
			}
			if (null != Objectlist) {
				Map<Object, Object> map = null;
				if (null != Objectlist && Objectlist.size() > 0) {
					for (Object[] numObj : Objectlist) {
						map = new HashMap<Object, Object>();
						map.put("id", numObj[0]);
						map.put("name", numObj[1]);
						map.put("organLevel", numObj[3]);
						map.put("province", numObj[4]);
						map.put("status", numObj[0]);
						map.put("createdate", numObj[2]);
						result.add(map);
						//System.out.println(numObj[0] + "/" + numObj[1]+ "/" + numObj[2]+ "/" + numObj[3]+ "/" + numObj[4]);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		String content = JsonUtil.formatToJson(result);
		super.pringWriterToPage(content);
		return null;
	}

	public List<Object[]> searchEthicsCommitteeList(String searchText,String provinceCode){
		if(searchText==null) {
			searchText = "";
		}
		if(provinceCode==null) {
			provinceCode = "";
		}
		int page = Integer.valueOf(pageIndex);
		int maxResult = Integer.valueOf(pageShowCount);
		//列表页
		List<Object[]> r2 = ethicsCommitteeRecordsService.findBySQL("select distinct top ( ("+page+"+1)*"+maxResult+") (t1.organization_id) as organization_id,t2.name as organization_name,t2.create_time,t2.organ_level,t3.name as province_name "+
				  " from work_ethics_committee_records t1 "+
				  " left join work_organization t2 on t1.organization_id=t2.id "+
				  " left join sys_province t3 on t1.province_id=t3.code "+
				  " where t1.status='"+state+"' and t2.name like '%"+ searchText +"%' and t1.province_id like '%"+ provinceCode +"%'  ");
		/*if (null != r2 && r2.size() > 0) {
			for (Object[] numObj : r2) {
				System.out.println(numObj[0] + "/" + numObj[1]+ "/" + numObj[2]+ "/" + numObj[3]+ "/" + numObj[4]);
			}
		}*/
			return r2;
	}
	
	public List<EthicsCommitteeRecords> searchEthicsCommitteeRecords(
			String sql, int firstResult, int maxResult) {
		List<EthicsCommitteeRecords> list = new ArrayList<EthicsCommitteeRecords>();
		
		try{
			if (state == 1) {
				if (null != province && province.length() > 0) {
					list = ethicsCommitteeRecordsService
							.findByPropertys(
									"o.organization.name like ? and o.status=? and o.organization.province.code=?",
									new Object[] { "%" + searchText + "%", state+"", province });
				} else {
					list = ethicsCommitteeRecordsService.findByPropertys(
							"o.organization.name like ? and o.status=?",
							new Object[] { "%" + searchText + "%", state+"" });
				}
			} else if (state == 2) {
				User userS = (User) getSession().getAttribute("user");
				list = ethicsCommitteeRecordsService
						.findByPropertys(
								"o.organization.name like ? and o.organization.province.code=? and o.status=?",
								new Object[] { "%" + searchText + "%",
										userS.getProvince().getCode(), 0+"" });

			}
			/*if (null != list) {
				result = Integer.valueOf(String.valueOf(list.size()));
			}*/
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		
		
		
		/*if (state == 1) {
			if (null != province && province.length() > 0) {
				list = ethicsCommitteeRecordsService
						.findByPropertys(
								firstResult,
								maxResult,
								"o.organization.name like ? and o.status=? and o.organization.province.code=?",
								new Object[] { "%" + sql + "%", state+"", province },
								null);
			} else {
				list = ethicsCommitteeRecordsService.findByPropertys(
						firstResult, maxResult,
						"o.organization.name like ? and o.status=?",
						new Object[] { "%" + sql + "%", state+"" }, null);
			}

		} else if (state == 2) {
			User userS = (User) getSession().getAttribute("user");
			list = ethicsCommitteeRecordsService
					.findByPropertys(
							firstResult,
							maxResult,
							"o.organization.name like ? and o.organization.province.code=? and o.status=?",
							new Object[] { "%" + sql + "%",
									userS.getProvince().getCode(), 0 }, null);
		}*/

		return list;
	}
/**
 * @author zf
 * @return 2017年2月17日15:08:39
 * @throws Exception start
 */
	//导航 ----1
	public String getProvinceList() throws Exception {

		List<Map<Object, Object>> list = new ArrayList<Map<Object, Object>>();
		List<Object[]> orglist = provinceService.findBySQL("select province_id,COUNT(province_id) cunt from (select wr.province_id ,organization_id from [ykyData].dbo.work_ethics_committee_records wr where status=1 group by wr.province_id,organization_id) temp group by province_id");
		
		
		Map<String, Object> provMap = new HashMap<String, Object>();
		if (null != orglist && orglist.size() > 0) {
			for (Object[] numObj : orglist) {
				provMap.put(numObj[0].toString(),numObj[1]);
			}
		}

		List<Province> provlist = provinceService.findEntityList();
		for (Province province : provlist) {
			Map<Object, Object> m = new HashMap<Object, Object>();
			m.put("name", province.getName());
			m.put("code", province.getCode());
			if (provMap.containsKey(province.getCode().toString())) {
				m.put("num", provMap.get(province.getCode().toString()));
			} else {
				m.put("num", "0");
			}
			list.add(m);
		}
		super.pringWriterToPage(JsonUtil.formatToJson(list));
		return null;
	}
	//导航  ---0
	public String getProvinceListo() throws Exception {

		List<Map<Object, Object>> list = new ArrayList<Map<Object, Object>>();
		List<Object[]> orglist = provinceService.findBySQL("select province_id,COUNT(province_id) cunt from (select wr.province_id ,organization_id from [ykyData].dbo.work_ethics_committee_records wr where status=0 group by wr.province_id,organization_id) temp group by province_id");
		
		
		Map<String, Object> provMap = new HashMap<String, Object>();
		if (null != orglist && orglist.size() > 0) {
			for (Object[] numObj : orglist) {
				provMap.put(numObj[0].toString(),numObj[1]);
			}
		}

		List<Province> provlist = provinceService.findEntityList();
		for (Province province : provlist) {
			Map<Object, Object> m = new HashMap<Object, Object>();
			m.put("name", province.getName());
			m.put("code", province.getCode());
			if (provMap.containsKey(province.getCode().toString())) {
				m.put("num", provMap.get(province.getCode().toString()));
			} else {
				m.put("num", "0");
			}
			list.add(m);
		}
		super.pringWriterToPage(JsonUtil.formatToJson(list));
		return null;
	}
	//详情查询
	public String findUserOrgById() {
		//User aUser = (User) super.getSession().getAttribute("user");
		//User aUser =userService.find(id);
		Organization organization=organizationService.find(id);
		Map<Object, Object> map = new HashMap<Object, Object>();
		map.put("org", organization);

		try {
			List<OrganizationRecords> list = organizationRecordsService.findByProperty("organization.id",id);

			if (null != list && list.size() > 0) {
				OrganizationRecords organizationRecords = list.get(0);
				map.put("orgRecords", organizationRecords);

				// List<OrganizationRecordsCertificate> ocList =
				// organizationRecordsCertificateService
				// .findByProperty("organizationRecords",
				// organizationRecords);
				// if (null != ocList && ocList.size() > 0) {
				// OrganizationRecordsCertificate organizationRecordsCertificate
				// = ocList
				// .get(0);
				// map.put("organizationRecordsCertificate",
				// organizationRecordsCertificate);
				// } else {
				// map.put("organizationRecordsCertificate", "");
				// }
			} else {
				map.put("orgRecords", "");
			}

			super.printWriterJsonToPage(JsonUtil.formatMapToJson(map));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	// 通过用户查询该用户所属机构的伦理备案信息
		public String getEthicsCommitteeRecordsListParticulars() throws Exception {
			//User aUser = (User) getSession().getAttribute("user");
			Organization organization=organizationService.find(id);
			if (organization != null) {
				Organization aOrganization = organization;
				List<EthicsCommitteeRecords> list = ethicsCommitteeRecordsService
						.findByPropertys("o.organization=?",
								new Object[] { aOrganization });
				String content = JsonUtil.formatToJson(list);
				super.pringWriterToPage(content);
				return null;
			}
			return null;
		}
		/** end */
	
		/**
		 * 2017年2月16日17:29:07
		 * @author zf  start
		 * @throws 伦理委员会备案审核
		 */
		// 通过
		public String editEthicsCommitteeRecordsSubmitPass() throws Exception {
			
				EthicsCommitteeRecords ethicsCommitteeRecords =ethicsCommitteeRecordsService.find(id);
				ethicsCommitteeRecords.setStatus("1");
				ethicsCommitteeRecordsService.updateEntity(ethicsCommitteeRecords);
					
				super.pringWriterToPage("success");
				return null;
			
		}
		// 未通过
		public String editEthicsCommitteeRecordsNoSubmitPass() throws Exception {
			EthicsCommitteeRecords ethicsCommitteeRecords =ethicsCommitteeRecordsService.find(id);
			ethicsCommitteeRecords.setStatus("2");
			ethicsCommitteeRecords.setReason(reason);
			ethicsCommitteeRecordsService.updateEntity(ethicsCommitteeRecords);
				
			super.pringWriterToPage("success");
			return null;
			
		}
		/** end  */
		
	public ProvinceService getProvinceService() {
		return provinceService;
	}

	public void setProvinceService(ProvinceService provinceService) {
		this.provinceService = provinceService;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getSearchText() {
		return searchText;
	}

	public void setSearchText(String searchText) {
		this.searchText = searchText;
	}

	public String getPageIndex() {
		return pageIndex;
	}

	public void setPageIndex(String pageIndex) {
		this.pageIndex = pageIndex;
	}

	public String getPageShowCount() {
		return pageShowCount;
	}

	public void setPageShowCount(String pageShowCount) {
		this.pageShowCount = pageShowCount;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getMemberName() {
		return memberName;
	}

	public void setMemberName(String memberName) {
		this.memberName = memberName;
	}

	public String getIsConstitution() {
		return isConstitution;
	}

	public void setIsConstitution(String isConstitution) {
		this.isConstitution = isConstitution;
	}

	public String getIsWorkingSystem() {
		return isWorkingSystem;
	}

	public void setIsWorkingSystem(String isWorkingSystem) {
		this.isWorkingSystem = isWorkingSystem;
	}

	public String getTelphone() {
		return telphone;
	}

	public void setTelphone(String telphone) {
		this.telphone = telphone;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getAttachmentPath() {
		return attachmentPath;
	}

	public void setAttachmentPath(String attachmentPath) {
		this.attachmentPath = attachmentPath;
	}

	public String getPracticeRegistrationAuthority() {
		return practiceRegistrationAuthority;
	}

	public void setPracticeRegistrationAuthority(
			String practiceRegistrationAuthority) {
		this.practiceRegistrationAuthority = practiceRegistrationAuthority;
	}

	public Organization getOrganization() {
		return organization;
	}

	public void setOrganization(Organization organization) {
		this.organization = organization;
	}

	public String getProvince() {
		return province;
	}

	public void setProvince(String province) {
		this.province = province;
	}

	public EthicsCommitteeRecords getEthicsCommitteeRecords() {
		return ethicsCommitteeRecords;
	}

	public void setEthicsCommitteeRecords(
			EthicsCommitteeRecords ethicsCommitteeRecords) {
		this.ethicsCommitteeRecords = ethicsCommitteeRecords;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getReason() {
		return reason;
	}

	public void setReason(String reason) {
		this.reason = reason;
	}

	public Integer getState() {
		return state;
	}

	public void setState(Integer state) {
		this.state = state;
	}

}
